package com.vitria.m3oui.rest.app.mgr;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import com.qilin.hammer.util.BaseRestService;

public class ConcurrentUserTest extends TestCase{
	public static String kpiUrlBase = "http://10.111.3.116:8080/m3oui/rest/app/sla/user/{user}/kpi/SLA_";
    public static String saveOp = "?op=save";
	public static String deployOp = "?op=deploy";
	public static String startOp = "?op=start&needDeploy=true";
	public static String stopOp = "?op=stop";
	public static String deleteOp = "?op=delete";
	public static String kpi1ContentFile = "D:/work/main/yoda/m3o/ui/devtests/junit/app.memory/resources/kpi1Content.txt";
	private Integer threshold = 0;
	private int threadNum = 100;
	private int userNum = 5;
	private int loops = 10;
	private Map<String, String> userTokens = new HashMap<String, String>();
	private String[] users = null;
	
	public ConcurrentUserTest(String name) {
        super(name);
    }
	
	@Override
	public void setUp(){
        users = new String[userNum];
        for(int i=0; i<userNum; i++)
        	users[i]="u"+String.valueOf(i+1);
	}
	
	public void testLoop() throws Exception {
		if(threadNum%userNum != 0)
			return;
    	final String document = readFromFile(kpi1ContentFile);
    	for(int i=0; i<userNum; i++){
    		userTokens.put(users[i], RestUtil.login(users[i], "123456"));
    	}
    	for(int i=0; i < loops+1; i++){
    		synchronized(threshold){
    			if(threshold == 0){
    				if(i == loops)
    					break;
    				threshold = threadNum;
    				System.out.println("Loop:"+(i+1));
    			} else {
    				Thread.sleep(1000);
    				i--;
    				continue;
    			}
    		}
    		int id = 0;
    		for(int j=0; j<threadNum; j++){
    			final String curuser = users[j%userNum];
    			if(j%userNum == 0)
    				id++;
    			final String kpiId =String.valueOf(id);
    			new Thread(){
    				public void run(){
    					try {
							//operationKPIModel(courser+"_"+kpiId, document, curuser);
    						listApp(RestUtil.login(curuser, "123456"));
				    		synchronized(threshold){
				    			threshold--;
				    		}
						} catch (Exception e) {
							e.printStackTrace();
						}
    				}
    			}.start();
    		}
    	}
    }
    
	private void listApp(String token){
		ClientResource resource = RestUtil.createSecureClientResource("http://10.111.3.116:8080/m3oui/rest/app.mgr/apps",userTokens.get(token));
		Representation rep = resource.get();
        try {
			String text = rep.getText();
			System.out.println("list... "+text);
		} catch (IOException e) {
			e.printStackTrace();
		}
       
	}
	
    private void operationKPIModel(String index, String document, String curuser) throws IOException{
 	 //KPI model test 
		String opString;
		String token = userTokens.get(curuser);
		String properties = "<properties><property name='tags' value=''/></properties>";
		
		Form form = new Form();
		form.add("_RESOURCE_Type", "kpi");
		form.add("document", document);
		form.add("properties", properties);
		form.add("space", "private");
		
		 // create KPI model SLA{$i}
		opString = kpiUrlBase.replace("{user}", curuser) + index + saveOp;
		ClientResource resource = RestUtil.createSecureClientResource(opString, token);
		Representation rep = resource.post(form.getWebRepresentation());
		String text = rep.getText();
		System.out.println("create KPI "+ index +" model:"+text);
		
		opString = kpiUrlBase.replace("{user}", curuser) + index  + startOp;
		resource = RestUtil.createSecureClientResource(opString, token);
		rep = resource.get();
		text = rep.getText();
		System.out.println("deploy and start KPI "+ index +" model:"+text);
		
		// stop KPI model
		opString = kpiUrlBase.replace("{user}", curuser) + index  + stopOp;
		resource = RestUtil.createSecureClientResource(opString, token);
		rep = resource.get();
		text = rep.getText();
		System.out.println("stop KPI "+ index +" model:"+text);
		
		// delete KPI model
		opString = kpiUrlBase.replace("{user}", curuser) + index  + deleteOp;
		resource = RestUtil.createSecureClientResource(opString, token);
		rep = resource.get();
		text = rep.getText();
		System.out.println("delete KPI "+ index +" model:"+text);
    }
    
    private static String readFromFile(String fileName) {
		try {
			StringBuilder sb = new StringBuilder();
			FileInputStream fstream = new FileInputStream(fileName);
			java.io.DataInputStream is = new java.io.DataInputStream(fstream);
			java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				sb.append(strLine);
			}
			is.close();
			return sb.toString();
		}
		catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}
		return null;
	}
}
